#include "Popup.h"
#include "../../core/Impp.h"
#include "../StdUserInterfaceModule/Icons.h"

namespace Impp
{

BEGIN_EVENT_TABLE(Popup, ImppPopupWindow)
  EVT_LEFT_DOWN(Popup::onLeftDown)
  EVT_RIGHT_DOWN(Popup::onRightDown)
END_EVENT_TABLE()
;


Popup::Popup(PopupService* service,const wxPoint & pos,const wxSize & size, Buddy* buddy,const wxString & txt,const wxColor & color, int time) :
	ImppPopupWindow(service->getDummyFrame()/*,wxID_ANY,wxT("popup"),pos,wxSize(100,50),wxFRAME_TOOL_WINDOW|wxFRAME_FLOAT_ON_PARENT*/),
	service(service),createTime(wxDateTime::GetTimeNow()),buddy(buddy),txt(txt),time(time)
{
	SetSize(size);
	SetPosition(pos);

	wxPanel* mainPane = new wxPanel(this);
	mainPane->SetPosition(wxPoint(2,2));
	mainPane->SetSize(size-wxSize(4,4));

	if(service->useColor()){
		mainPane->SetBackgroundColour(color);
		SetBackgroundColour(color);
	}

	int alpha = service->getAlpha();
	if(alpha!=255){
		SetTransparent(alpha);
	}


	wxStaticText* staticTxt = new wxStaticText(mainPane,wxID_ANY,txt);
	wxFont f = staticTxt->GetFont();
	f.SetPointSize(8);
	staticTxt->SetFont(f);


	if(buddy==NULL){

		staticTxt->Wrap(size.GetWidth()-4);
	}else{
		wxBitmap ava = buddy->getAvatar();
		if(ava.IsNull()){
			iUserInterface* ui = Impp::exemplar()->getModuleManager()->getUserInterfaceModule();
			if(ui != NULL){
				ava = ui->getIcons()->getSpecialBitmap(BITMAP_NO_AVATAR);
			}
		}
		wxImage image = ava.ConvertToImage();
		wxBitmap avaScaled = wxBitmap(image.Scale(32,32,wxIMAGE_QUALITY_HIGH));
		wxStaticBitmap* avatarBitmap = new wxStaticBitmap(mainPane,wxID_ANY,avaScaled);
		wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);

		staticTxt->Wrap(size.GetWidth()-36);

		sizer->Add(avatarBitmap,0,wxALL,5);
		sizer->Add(staticTxt,1,wxALL,5);

		mainPane->SetSizer(sizer);
		mainPane->Layout();
		mainPane->Connect(wxEVT_LEFT_DOWN,wxMouseEventHandler(Popup::onLeftDown),NULL,this);
		mainPane->Connect(wxEVT_RIGHT_DOWN,wxMouseEventHandler(Popup::onRightDown),NULL,this);
		staticTxt->Connect(wxEVT_LEFT_DOWN,wxMouseEventHandler(Popup::onLeftDown),NULL,this);
		staticTxt->Connect(wxEVT_RIGHT_DOWN,wxMouseEventHandler(Popup::onRightDown),NULL,this);
		avatarBitmap->Connect(wxEVT_LEFT_DOWN,wxMouseEventHandler(Popup::onLeftDown),NULL,this);
		avatarBitmap->Connect(wxEVT_RIGHT_DOWN,wxMouseEventHandler(Popup::onRightDown),NULL,this);

	}

	Layout();
	Show();


}

Popup::~Popup()
{
}

void Popup::onLeftDown(wxMouseEvent & event){
	if(buddy!=NULL){
		iChatWindow* cw = Impp::exemplar()->getModuleManager()->getChatWindowModule();
		if(cw != NULL){
			cw->showChatWindow(buddy);
		}else{
			wxLogDebug(wxT("No Chatwindow that could be showen"));
		}
	}
}
void Popup::onRightDown(wxMouseEvent & event){
	service->hidePopup(this);
}

bool Popup::isTimedOut(time_t & now){
	if(time==-1){
		return false;
	}
	return now > createTime+(time_t)time;
}


}
